/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.approval.dto.MemberUserVo;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalWaitRecordMapper;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.DistributionDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.EditDistributionDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseDistributionEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDistributionRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseHandlePersonRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesLegalInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDistributionRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseHandlePersonRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfoStatusChangeRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDistributionRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoStatusChangeRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.DistributionVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeTypeEnum;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.Collator;
import java.util.*;

/**
 * 描述:  case_distribution_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年11月15日
 */
@Service
@RefreshScope
public class CaseDistributionRecordServiceImpl extends MyBatisServiceSupport implements ICaseDistributionRecordService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseDistributionRecordServiceImpl.class);

    @Resource
    private CaseDistributionRecordMapper caseDistributionRecordMapper;
    @Resource
    private CasePartiesRecordServiceImpl casePartiesRecordService;
    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    @Resource
    private CaseApprovalWaitRecordMapper caseApprovalWaitRecordMapper;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private IRegisterCommonService commonService;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private ICaseMainInfoStatusChangeRecordService caseMainInfoStatusChangeRecordService;
    @Value("${isCheckHandleSign}")
    private String isCheckHandleSign;
    @Value("${member.url}")
    private String url;
    @Value("${member.api.getZfPeopleList}")
    private String zfPeopleListUrl;
    @Value("${approval.center.legalRoleId}")
    private String legalRoleId;

    /**
     * 描述: 分配法制人员-分配列表
     *
     * @param distributionDto
     * @return com.icinfo.framework.common.web.Result
     * @author zhanghongqiang
     * @Date 2022/11/15
     */
    @Override
    public List<DistributionVo> getDistributionList(DistributionDto distributionDto) {
        //登录人和机构判断
        checkOrgCode(distributionDto);
        distributionDto.setCaseTerritoryCode(Constant.ECOLOGICAL_LINE_CODE);
        PageHelper.startPage(distributionDto.getPageNum(), distributionDto.getLength());
        List<DistributionVo> voList = caseDistributionRecordMapper.selectDistributionList(distributionDto);
        if (!ObjectUtils.isEmpty(voList)) {
            for (DistributionVo vo : voList) {
                vo.setAllocationStatusCn(CaseDistributionEnum.getValueByCode(vo.getAllocationStatus()));
                //鉴定 中止与恢复 办案期限计算
                CaseMainInfoStatusChangeRecord record = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(vo.getCaseId(), CaseStatusChangeTypeEnum.SUSPEND.getCode());
                if (null != record) {
                    //暂停，则原有的办案期限+（当前日期-中止日期）
                    if (Constant.STRING_1.equals(record.getStatus())) {
                        long days = DateUtil.calculatePastDays(record.getChangeEffectTime().toLocalDate());
                        vo.setCaseTimeLimit(DateUtils.addDays(vo.getCaseTimeLimit(), (int) days));
                    }
                    //恢复，则原有的办案期限+（恢复日期-中止日期）
                }
                vo.setTimeColor("");
                if (vo.getCaseTimeLimit() != null && vo.getCaseVerdictEndTime() == null
                        && !CaseStatusEnum.END_CASE.getCode().equals(vo.getCaseStatus())
                        && !CaseStatusEnum.END_CRIMINAL_TRANSFER.getCode().equals(vo.getCaseStatus())
                        && !CaseStatusEnum.TRANSFERRING.getCode().equals(vo.getCaseStatus())
                ) {
                    //todo
                    int timeLimit = BaseUtil.getBetweenDays(BaseUtil.getTodayStartDate(), vo.getCaseTimeLimit());
                    if (timeLimit == Constant.INTEGER_0) {
                        vo.setRemainTime("截止日");
                    } else if (timeLimit > Constant.INTEGER_0) {
                        vo.setRemainTime("剩余" + timeLimit + "天");
                    } else {
                        vo.setRemainTime("超" + String.valueOf(timeLimit).substring(Constant.INTEGER_1) + "天");
                    }
                    //分红（当前日期-办案期限<0)、黄(当前日期-办案期限<=7)、蓝色(当前日期-办案期限>7)
                    if (timeLimit < Constant.INTEGER_0) {
                        vo.setTimeColor("red");
                    } else if (timeLimit <= Constant.INTEGER_7) {
                        vo.setTimeColor("yellow");
                    } else if (timeLimit > Constant.INTEGER_7) {
                        vo.setTimeColor("blue");
                    }
                    //暂停设置为灰色
                    if (CaseStatusEnum.SUSPEND.getCode().equals(vo.getCaseStatus())) {
                        vo.setTimeColor("gray");
                    }
                }
                // 当事人
                List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(vo.getCaseId());
                if (!ObjectUtils.isEmpty(casePartiesRecords) && casePartiesRecords.size() > 0) {
                    String partyName = casePartiesRecords.get(0).getPartyName();
                    String partyType = casePartiesRecords.get(0).getPartyType();
                    String partyId = casePartiesRecords.get(0).getPartyId();
                    if (casePartiesRecords.size() > 1) {
                        vo.setPartyType("multitude");
                        vo.setPartyName(partyName + "等" + casePartiesRecords.size() + "个");
                    } else {
                        vo.setPartyType(partyType);
                        vo.setPartyName(partyName);
                        if (Constant.STRING_2.equals(partyType)){
                            vo.setUniscid(casePartiesLegalInfoMapper.selectByPrimaryKey(partyId).getUniscid());
                        }
                    }
                }
            }
        }
        return voList;
    }

    private void checkOrgCode(DistributionDto distributionDto) {
        distributionDto.setOrg(0);
        if (StringUtils.isEmpty(distributionDto.getOrgCode())) {
            return;
        }
        List<String> orgCodeList = new ArrayList<>();
        List<String> deptCodeList = new ArrayList<>();
        String[] str = distributionDto.getOrgCode().split(",");
        for (String s : str) {
            if (s.indexOf("_") > 0) {
                orgCodeList.add(s);
            } else {
                deptCodeList.add(s);
            }
        }
        if (orgCodeList.size() > 0 && deptCodeList.size() > 0) {
            distributionDto.setOrg(1);
        } else if (orgCodeList.size() > 0) {
            distributionDto.setOrg(2);
        } else if (deptCodeList.size() > 0) {
            distributionDto.setOrg(3);
        }
        distributionDto.setOrgCodeList(orgCodeList);
        distributionDto.setDeptCodeList(deptCodeList);
    }

    /**
     * 描述: 不存在插入数据
     *
     * @param caseId
     * @return void
     * @author zhanghongqiang
     * @Date 2022/11/15
     */
    @Override
    public void insertDistribution(String caseId) {
        CaseDistributionRecord ca = new CaseDistributionRecord();
        ca.setCaseId(caseId);
        CaseDistributionRecord caseDistributionRecord = caseDistributionRecordMapper.selectOne(ca);
        if (ObjectUtils.isEmpty(caseDistributionRecord)) {
            ca.setId(StringUtils.uuid());
            caseDistributionRecordMapper.insertSelective(ca);
        }
    }

    /**
     * 描述: 分配法制人员-分配操作
     *
     * @param editDistributionDto
     * @return com.icinfo.framework.common.web.Result
     * @author zhanghongqiang
     * @Date 2022/11/15
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editDistribution(EditDistributionDto editDistributionDto) {
        String userId = editDistributionDto.getUserId();
        CaseHandlePersonRecord caseHandlePersonRecord = new CaseHandlePersonRecord();
        caseHandlePersonRecord.setHandlePersonType("3");
        caseHandlePersonRecord.setHandlePersonId(userId);
        if (ObjectUtil.isNotEmpty(userId)) {
            String lawEnforcementCert = xzzfInterfaceService.getLawEnforcementCertWithUserId(userId);
            if (ObjectUtil.isEmpty(lawEnforcementCert)) {
                throw new BusinessException("办案人员UserId" + userId + "的执法证为空!");
            }
            caseHandlePersonRecord.setLawEnforcementCert(lawEnforcementCert);
        }
        //  签名校验
        String handlePersonSignPic = null;
        try {
            handlePersonSignPic = commonService.getHandleSignData(userId);
        } catch (Exception e) {
            e.printStackTrace();
            if ("true".equals(isCheckHandleSign)) {
                if (ObjectUtil.isEmpty(handlePersonSignPic)) {
                    throw new BusinessException("因未获取承办人员用户id:" + userId + "有效签名信息，无法提交");
                }
            }
        }
        caseHandlePersonRecord.setHandleSignPic(handlePersonSignPic);
        caseHandlePersonRecord.setStatus(Constant.STRING_1);
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new BusinessException("未获取到登录人!");
        }
        //机构手机号码
        caseHandlePersonRecord.setHandleOrgTel(userInfo.getTelPhone());
        //部门手机号码
        caseHandlePersonRecord.setHandleDeptTel(userInfo.getTelPhone());
        getUserInfoByUserId(caseHandlePersonRecord);
        List<String> caseIds = editDistributionDto.getCaseId();
        if (!ObjectUtils.isEmpty(caseIds) && caseIds.size() > 0) {
            for (String caseId : caseIds) {
                caseHandlePersonRecord.setId(BaseUtil.createUid());
                caseHandlePersonRecord.setCaseId(caseId);
                caseHandlePersonRecord.setAddTime(new Date());
                caseHandlePersonRecordMapper.insertSelective(caseHandlePersonRecord);
            }
        }
        // 新增成功法制人员再修改状态
        CaseDistributionRecord caseDistributionRecord = new CaseDistributionRecord();
        caseDistributionRecord.setUserId(userId);
        caseDistributionRecord.setAllocationStatus(Constant.STRING_2);
        List<String> ids = editDistributionDto.getId();
        if (!ObjectUtils.isEmpty(ids) && ids.size() > 0) {
            for (String id : ids) {
                caseDistributionRecord.setId(id);
                caseDistributionRecord.setAllocationTime(new Date());
                caseDistributionRecordMapper.updateByPrimaryKeySelective(caseDistributionRecord);
            }
        }
    }


    /**
     * 描述: 分配法制人员-分配弹窗
     *
     * @return com.icinfo.framework.common.web.Result
     * @author zhanghongqiang
     * @Date 2022/11/15
     */
    @Override
    public List<MemberUserVo> getDistributionPeople(String caseOrgCode) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new BusinessException("未获取到登录人!");
        }
        if (StringUtils.isBlank(caseOrgCode)) {
            caseOrgCode = userInfo.getOrgCode();
        }
        Map<String, Object> paramMap = new HashMap<>(16);
        paramMap.put("orgCode", caseOrgCode);
        // 法制人员角色id
        paramMap.put("roleId", legalRoleId);
        List<MemberUserVo> memberUserVos = caseApprovalWaitRecordMapper.selectMemberUserVoList(paramMap);
        if (!ObjectUtils.isEmpty(memberUserVos)) {
            //法制人员列表增加按姓名排序
            Collator china = Collator.getInstance(Locale.CHINA);
            Collections.sort(memberUserVos, (o1, o2) -> china.compare(o1.getRealName(), o2.getRealName()));
        }
        return memberUserVos;
    }

    /**
     * 描述: 通过用户唯一userId获取人员信息
     *
     * @author zhanghongqiang
     * @Date 2022/11/16
     */
    public void getUserInfoByUserId(CaseHandlePersonRecord caseHandlePersonRecord) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        JSONObject json = new JSONObject();
        List<String> userIds = new ArrayList<>();
        userIds.add(caseHandlePersonRecord.getHandlePersonId());
        json.put("userIds", userIds);
        json.put("pageNum", 1);
        json.put("length", 1);
        json.put("hasCert", Constant.STRING_1);
        json.put("searchType", Constant.STRING_1);
        String param = json.toJSONString();
        String response = HttpUtil.createPost(url.concat(zfPeopleListUrl)).addHeaders(headers).body(param).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getIntValue("code") == 200) {
            JSONArray ja = jsonObject.getJSONObject("data").getJSONArray("data");
            if (ja == null || ja.size() == 0) {
                logger.info("=======没有数据=======");
            }
            JSONObject obj = (JSONObject) ja.get(0);
            if (!ObjectUtils.isEmpty(obj)) {
                caseHandlePersonRecord.setHandlePersonName(obj.getString("realName"));
                caseHandlePersonRecord.setHandleOrgName(obj.getString("orgName"));
                caseHandlePersonRecord.setHandleOrgCode(obj.getString("orgCode"));
                caseHandlePersonRecord.setHandleDeptName(obj.getString("deptName"));
                caseHandlePersonRecord.setHandleDeptCode(obj.getString("deptCode"));
                caseHandlePersonRecord.setDingId(obj.getString("zwdAccountId"));
                caseHandlePersonRecord.setHandlePersonTel(obj.getString("phone"));
            }
        }
    }
}